package com.ang.interceptor;

import com.ang.annotation.SensitiveEntity;
import com.ang.annotation.SensitiveField;
import com.ang.utils.Base64Util;
import com.baomidou.mybatisplus.annotation.TableId;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.Invocation;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Optional;

/**
 * @author ssang
 * @date 2022-09-27 16:46
 */
@Component
public class CommonUtil {
    /**
     * 执行sql，还原加解密后的报文
     */
    Object proceed(Invocation invocation, MappedStatement mappedStatement, Object parameter) throws Throwable {
        //先复制一个对象备份数据
        Object newInstance = newInstance(parameter);
        //调用加解密服务
        try {
            encrypt(parameter);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //执行操作，得到返回结果
        Object result = invocation.proceed();
        //把加解密后的字段还原
        reductionParameter(mappedStatement, newInstance, parameter);
        //返回结果
        return result;
    }

    /**
     * 先复制一个对象备份数据,便于加解密后还原原报文
     */
    private Object newInstance(Object parameter) throws IllegalAccessException, InstantiationException {
        Object newInstance = parameter.getClass().newInstance();
        BeanUtils.copyProperties(parameter, newInstance);
        return newInstance;
    }

    /**
     * 把加解密后的字段还原，同时把mybatis返回的tableId返回给参数对象
     */
    private void reductionParameter(MappedStatement mappedStatement, Object newInstance, Object parameter) throws IllegalAccessException {
        //获取映射语句命令类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        if (SqlCommandType.INSERT == sqlCommandType) {
            //从参数属性中找到注解是TableId的字段
            Field[] parameterFields = parameter.getClass().getDeclaredFields();
            Optional<Field> optional = Arrays.stream(parameterFields).filter(field -> field.isAnnotationPresent(TableId.class)).findAny();
            if (optional.isPresent()) {
                Field field = optional.get();
                field.setAccessible(true);
                Object id = field.get(parameter);
                //覆盖参数加解密的值
                BeanUtils.copyProperties(newInstance, parameter);
                field.set(parameter, id);
            } else {
                //覆盖参数加解密的值
                BeanUtils.copyProperties(newInstance, parameter);
            }
        } else {
            //覆盖参数加解密的值
            BeanUtils.copyProperties(newInstance, parameter);
        }
    }

    /**
     * 是否需要加解密：
     * ① 是否属于基本类型，void类型和String类型，如果是，不加解密
     * ② 实体类上是否有注解
     * ③ 属性是否有注解
     *
     * @param object
     * @return
     */
    public boolean needToCrypt(Object object) {
        if (object == null) {
            return false;
        }
        Class<?> clazz = object.getClass();
        if (clazz.isPrimitive() || object instanceof String) {
            //基本类型和字符串不加解密
            return false;
        }
        //获取实体类注解
        boolean annotationPresent = clazz.isAnnotationPresent(SensitiveEntity.class);
        if (!annotationPresent) {
            //无注解不加解密
            return false;
        }
        //获取属性注解
        Field[] fields = clazz.getDeclaredFields();
        return Arrays.stream(fields).anyMatch(field -> field.isAnnotationPresent(SensitiveField.class));
    }

    /**
     *
     * @param parameterObject 需要加密的对象
     * @return
     * @throws Exception
     */
    public Object encrypt(Object parameterObject) throws Exception {
        //Mapper参数类型，为Map
        if(parameterObject instanceof HashMap){
            ((HashMap) parameterObject).forEach((k,v) -> {
                if(k.equals("name")){
                    String newVal = Base64Util.encrypt(String.valueOf(v));
                    ((HashMap) parameterObject).put(k,newVal);
                }
            });
        }
        //Mapper参数类型，为对象
        else{
            Field[] declaredFields = parameterObject.getClass().getDeclaredFields();
            for (Field field : declaredFields) {
                // 取出所有被encryptDecryptField注解的字段
                SensitiveField cryptAnnotation = field.getAnnotation(SensitiveField.class);
                if (cryptAnnotation != null) {
                    // accessible指示反射的对象爱使用时取消java语言访问检查
                    field.setAccessible(true);
                    Object obj = field.get(parameterObject);
                    // 只对String类型进行加密
                    if (obj instanceof String) {
                        String val = obj.toString();
                        // 如果有标识则不加密，没有则加密并加上标识前缀
                        field.set(parameterObject, Base64Util.encrypt(val));
                    }
                }
            }
        }
        return parameterObject;
    }
}
